package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.*;
import com.gable.exhibition.model.Appoint;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.RepairService;
import com.gable.exhibition.service.UserService;
import com.gable.exhibition.util.ExceptionUtil;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 乔春峰 on 2018/1/4.
 * 维修controller
 */
@Controller
@RequestMapping(value="/repair")
public class RepairController {

    Logger logger = Logger.getLogger(RepairController.class);

    @Autowired
    RepairService repairService;

    @Autowired
    UserService userService;

    /**
     * 跳转页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/page")
    public String page(HttpServletRequest request, HttpServletResponse response){
        return "repair/repair-page";
    }

    /**
     * 跳转详情
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping(value="/info")
    public String info(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true) Long id){
        return "repair/repair-info";
    }

    /**
     * 维修详情
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="/details",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil details(HttpServletRequest request, HttpServletResponse response,RepairView repairView){
        try{
            Long repairId = repairView.getRepairId();
            if(repairId == null)
                return new ReturnResultUtil(500,MessageUtil.REPAIRIDISNULL);
            UserView sessionUser = CacheData.getSessionUser(repairView.getUserId(), 1);
            if(sessionUser == null)
                sessionUser = CacheData.getSessionUser(null,2);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            repairView.setUserId(sessionUser.getUserId());
            ReturnResultUtil rru =repairService.details(repairView);
            logger.debug(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
        }
    }

    /**
     * 添加报修
     * @param repair
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil add(RepairView repair){
        if(repair.getDeviceId() == null){
            return new ReturnResultUtil(500,MessageUtil.DEVICEIDISNULL);
        }
         try {
             // 获取当前登陆用户信息
             Long userId = repair.getUserId();
             UserView sessionUser = CacheData.getSessionUser(userId, 1);
             if(sessionUser == null)
                 return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
             return repairService.add(repair);
         }catch (ExceptionUtil e){
             return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
         }catch (Exception e){
             e.printStackTrace();
             return new ReturnResultUtil(500, MessageUtil.FAILED);
         }
    }

    /**
     * 查询维修list
     * @param request
     * @param response
     * @param repairView
     * @return
     */
    @RequestMapping(value="/list",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil list(HttpServletRequest request, HttpServletResponse response, RepairView repairView){
        try{
            UserView sessionUser = CacheData.getSessionUser(repairView.getUserId(), 1);
            if(sessionUser == null)
                sessionUser = CacheData.getSessionUser(null,2);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);

            if (sessionUser.getType() == 1101) {
                repairView.setHospitalId(sessionUser.getHospitalId());
                repairView.setRole(1);
            } else if(sessionUser.getTag() == 1004 || sessionUser.getTag() == 1006 || sessionUser.getTag() ==1009) {
                repairView.setRole(3);
                repairView.setEngineerId(sessionUser.getUserId());
            }else if(sessionUser.getType() == 1102 || sessionUser.getType() == 1103 || sessionUser.getType() ==1105){
                repairView.setRole(2);
                repairView.setServiceType(sessionUser.getType());
                if(sessionUser.getType() == 1102){
                    repairView.setServiceId(sessionUser.getManufacturerId());
                }else if(sessionUser.getType() == 1103){
                    repairView.setServiceId(sessionUser.getMaintainerId());
                }else if(sessionUser.getType() == 1105){
                    repairView.setServiceId(sessionUser.getSupplierId());
                }
            }else if(sessionUser.getType() == 1104){
                repairView.setRole(4);
            }
            ReturnResultUtil rru = repairService.list(repairView);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }

    /**
     * 平台审核通过
     * @param request
     * @param repairView
     * @return
     */
    @RequestMapping(value="/agree",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil agree(HttpServletRequest request, RepairView repairView){
        try{
            UserView sessionUser = CacheData.getSessionUser(repairView.getUserId(), 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            String serviceName = repairView.getServiceName();
            String serviceContacts = repairView.getServiceContacts();
            String servicePhone = repairView.getServicePhone();
            if(repairView.getRepairId()==null)
                return new ReturnResultUtil(500,MessageUtil.REPAIRIDISNULL);
            if(StringUtil.isEmpty(serviceName))
                return new ReturnResultUtil(500,MessageUtil.MAINTAINERNAMEISNULL);
            if(StringUtil.isEmpty(serviceContacts))
                return new ReturnResultUtil(500,MessageUtil.MAINTAINERCONTACTSISNULL);
            if(StringUtil.isEmpty(servicePhone))
                return new ReturnResultUtil(500,MessageUtil.MAINTAINERPHONEISNULL);
            //平台处理人
            repairView.setTerraceHandlePerson(sessionUser.getUserId());
            repairView.setHandleTime(DateUtils.getCurrentTime());
            ReturnResultUtil rru = repairService.agree(repairView);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.FAILED);
    }

    /**
     * 平台审核不通过
     * @param request
     * @param repairView
     * @return
     */
    @RequestMapping(value="/disagree",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil disagree(HttpServletRequest request, RepairView repairView){
        try{
            UserView sessionUser = CacheData.getSessionUser(repairView.getUserId(), 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            //平台处理人
            repairView.setTerraceHandlePerson(sessionUser.getUserId());
            repairView.setHandleTime(DateUtils.getCurrentTime());
            return repairService.disagree(repairView);
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.FAILED);
    }


    /**
     * 分配
     * @param request
     * @return
     */
    @RequestMapping(value="/distribution",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil distribution(HttpServletRequest request, RepairView repairView){
        try{
            UserView sessionUser = CacheData.getSessionUser(repairView.getUserId(), 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            Integer isDispatch = repairView.getIsDispatch();
            Long repairId = repairView.getRepairId();
            if(repairId == null){
                return new ReturnResultUtil(500,MessageUtil.REPAIRIDISNULL);
            }
            if(isDispatch == 1){
                String engineerPhone = repairView.getEngineerPhone();
                String engineerName = repairView.getEngineerName();
                if(StringUtil.isEmpty(engineerName))
                    return new ReturnResultUtil(500,MessageUtil.PROJECTCHARGEPERSON);
                if(StringUtil.isEmpty(engineerPhone))
                    return new ReturnResultUtil(500,MessageUtil.PROJECTCHARGEPERSONPHONE);
            }
            repairView.setTerraceHandlePerson(sessionUser.getUserId());
            return repairService.distribution(repairView,sessionUser);
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
        }
    }

    /**
     * 工程师响应时间
     * @param repairView
     * @return
     */
    @RequestMapping(value="/engineerResponse",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil engineerResponse(RepairView repairView){
        try{
            UserView sessionUser = CacheData.getSessionUser(repairView.getUserId(), 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            if(repairView.getRepairId() == null){
                return new ReturnResultUtil(500,MessageUtil.REPAIRIDISNULL);
            }
            return repairService.engineerResponse(repairView);
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(500, MessageUtil.FAILED);
        }
    }

    /**
     * 工程师开始维修
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="/startRepair",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil startRepair(HttpServletRequest request, HttpServletResponse response, RepairView repairView){
        try{
            // 获取当前登陆用户信息
            Long userId = repairView.getUserId();
            if(userId == null)
                return new ReturnResultUtil(500,MessageUtil.USERIDDOESTNOEXIST);
            UserView sessionUser = CacheData.getSessionUser(userId, 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            if(repairView.getRepairId() == null){
                return new ReturnResultUtil(500,MessageUtil.REPAIRIDISNULL);
            }
            return repairService.startRepair(repairView);
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(500, MessageUtil.FAILED);
        }
    }

    /**
     * 维修确认
     * @param request
     * @param response
     * @param repair
     * @return
     */
    @RequestMapping(value="/confirm",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil confirm(HttpServletRequest request, HttpServletResponse response, RepairView repair){
        if(repair.getRepairId() == null){
            return new ReturnResultUtil(500,MessageUtil.REPAIRIDISNULL);
        }
        if(repair.getStatus() == null){
            return new ReturnResultUtil(500,MessageUtil.STATUSISNULL);
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long userId = repair.getUserId();
        User user = CacheData.getSessionUser(null,1);
        if(user == null){
            user = CacheData.getSessionUser(userId,1);
        }
        if(user == null)
            return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
        repair.setHospitalConfirmPerson(user.getUserId());          // 确认人
        repair.setHospitalConfirmTime(DateUtils.getCurrentTime());  // 确认时间
        try{
            return repairService.confirm(repair);
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(500, MessageUtil.FAILED);
        }
    }

    /**
     * 维修信息补全
     * @param request
     * @param repairView
     * @return
     */
    @RequestMapping(value="/saveRepairData",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveRepairData(HttpServletRequest request, RepairView repairView){
        try{
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Long userId = repairView.getUserId();
            User user = CacheData.getSessionUser(null,1);
            if(user == null){
                user = CacheData.getSessionUser(userId,1);
            }
            if(user == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            Long repairId = repairView.getRepairId();
            if(repairId == null){
                return new ReturnResultUtil(500,MessageUtil.REPAIRIDISNULL);
            }
//            Integer travelTime =repairView.getTravelTime();
//            String repairEndTime = repairView.getRepairEndTime();
//            Long repairDeviceEndStatus = repairView.getRepairDeviceEndStatus();
//            String repairContent = repairView.getRepairContent();
            repairView.setUpdateTime(df.format(new Date()));
            repairView.setUpdatePerson(user.getUserId());
            repairView.setStatus(2203L);

            ReturnResultUtil rru = repairService.saveRepairData(repairView,user);
            return rru;
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }

//    //维修提醒
//    @RequestMapping(value="/queryRemind",method = RequestMethod.POST, produces="application/json;charset=utf-8")
//    @ResponseBody
//    public ReturnResultUtil queryRemind(HttpServletRequest request, ParameterView parameterView){
//        ReturnResultUtil resultUtil = new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
//        try {
//            UserView sessionUser = CacheData.getSessionUser(parameterView.getUserId(), 1);
//            if(sessionUser == null)
//                sessionUser = CacheData.getSessionUser(null,2);
//            if(sessionUser == null)
//                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
//            Long manufacturerId = sessionUser.getManufacturerId();
//            String s = "";//ManufacturerInit.manufacturerMaintainerMap.get(manufacturerId);
//            if(!StringUtil.isEmpty(s)){
//                String[] split = s.split(",");
//                List<String> strings = Arrays.asList(split);
//                parameterView.setMaintainers(strings);
//            }
//
//            resultUtil = repairService.queryRemind(parameterView);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return resultUtil;
//    }

    /**
     * 查询维修医院端、平台新建界面
     * @param request
     * @param response
     * @param repairView
     * @return
     */
    @RequestMapping(value="/queryInfoPage",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryInfoPage(HttpServletRequest request, HttpServletResponse response, RepairView repairView){
        try{
            UserView sessionUser = CacheData.getSessionUser(repairView.getUserId(), 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            ReturnResultUtil rru = repairService.queryInfoPage(repairView,sessionUser);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }

    /**
     * 平台、供应商、厂商、维修商修改指派工程师
     * @param request
     * @param response
     * @param appoint
     * @return
     */
    @RequestMapping(value="/editEngineer",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil editEngineer(HttpServletRequest request, HttpServletResponse response, Appoint appoint){
        try{
            Long userId = null;
            if(!StringUtil.isEmpty(request.getParameter("userId"))){
                userId = Long.parseLong(request.getParameter("userId"));
            }

            User user = CacheData.getSessionUser(userId,1);

            if(appoint.getAppointId() == null){
                return new ReturnResultUtil(500,MessageUtil.APPOINTIDISNULL);
            }
            if(StringUtil.isEmpty(appoint.getEngineerName())){
                return new ReturnResultUtil (500,MessageUtil.ENGINEERINFOISNULL);
            }
            if(StringUtil.isEmpty(appoint.getEngineerPhone())){
                return new ReturnResultUtil(500,MessageUtil.ENGINEERPHONEISNULL);
            }
            appoint.setCreatePerson(user.getUserId());
            ReturnResultUtil rru = repairService.editEngineer(appoint,user);
            return rru;
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }

    /* 维修不通过
     * @param request
     * @param response
     * @param repairView
     * @return
     */
//    @RequestMapping(value="/reject",method = RequestMethod.POST, produces="application/json;charset=utf-8")
//    @ResponseBody
//    public ReturnResultUtil reject(HttpServletRequest request, HttpServletResponse response, RepairView repairView){
//        try{
//            UserView sessionUser = CacheData.getSessionUser(repairView.getUserId(), 1);
//            if(sessionUser == null)
//                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
//            if(repairView.getRepairId() == null){
//                return new ReturnResultUtil(500,MessageUtil.REPAIRIDISNULL);
//            }
//            ReturnResultUtil rru = repairService.reject(repairView);
//            return rru;
//        }catch (ExceptionUtil e){
//            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
//    }

    /**查询所选设备是否正在维修
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="/queryDeviceIsRepair",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryDeviceIsRepair(HttpServletRequest request,HttpServletResponse response){
        try{
            if(StringUtil.isEmpty(request.getParameter("deviceId"))){
                new ReturnResultUtil(500,MessageUtil.DEVICEIDISNULL);
            }
            Long deviceId = Long.parseLong(request.getParameter("deviceId"));
            return repairService.queryDeviceIsRepair(deviceId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
    }

    //维修提醒
    @RequestMapping(value="/queryRemind",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryRemind(HttpServletRequest request,HttpServletResponse response){
        try{
            Long userId = null;
            if(!StringUtil.isEmpty(request.getParameter("userId"))){
                userId = Long.parseLong(request.getParameter("userId"));
            }
            User user = CacheData.getSessionUser(userId,1);
            Map map = new HashMap();
            if(user.getType() == 1101L){
                map.put("role",1);
                map.put("hospitalId",user.getHospitalId());
                map.put("createPerson",user.getUserId());
            }else if(user.getTag() == 1004L || user.getTag() == 1006L || user.getTag() ==1009L) {
                map.put("role",3);
                map.put("engineerId",user.getUserId());
            }else if(user.getType() == 1102L || user.getType() == 1103L || user.getType() ==1105L){
                map.put("role",2);
                map.put("serviceType",user.getType());
                if(user.getType() == 1102L){
                    map.put("serviceId",user.getManufacturerId());
                }else if(user.getType() == 1103L){
                    map.put("serviceId",user.getMaintainerId());
                }else if(user.getType() == 1105L){
                    map.put("serviceId",user.getSupplierId());
                }
            }
            ReturnResultUtil rru = repairService.queryRemind(map);
            logger.debug(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
    }

    /**
     * 无设备添加报修
     * @param repair
     * @return
     */
    @RequestMapping(value = "/addRepair",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public String addRepair(RepairView repair){
        try {
            // 获取当前登陆用户信息
//            Long userId = repair.getUserId();
//            UserView sessionUser = CacheData.getSessionUser(userId, 1);
//            if(sessionUser == null)
//                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            ReturnResultUtil returnResultUtil = repairService.addRepair(repair);
            return JSON.toJSONString(returnResultUtil);
        }catch (ExceptionUtil e){
            return JSON.toJSONString(new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData()));
        }catch (Exception e){
            e.printStackTrace();
            return JSON.toJSONString(new ReturnResultUtil(500, MessageUtil.FAILED));
        }
    }
}
